package com.apexsoft.monitor.front.console.magent.service;


import com.alibaba.fastjson.JSONObject;
import com.apexsoft.front.common.support.Result;
import com.apexsoft.front.common.utils.SpringContextUtil;
import com.apexsoft.monitor.front.console.host.om.Host;
import com.apexsoft.monitor.front.console.host.service.HostService;
import com.apexsoft.monitor.front.console.magent.om.Observer;
import com.apexsoft.monitor.front.console.magent.om.Subject;
import com.apexsoft.monitor.front.console.scheme.om.Scheme;
import com.apexsoft.monitor.front.console.scheme.service.SchemeService;

import java.util.*;


public class MonitorThread extends Thread implements Subject{

    //轮询执行时间ms
    private long sleepTime = 5000;

    private HostService hostService = null;

    private SchemeService schemeSvc = null;

    public static  Map<String,Observer> magentMap = null;//new Hashtable<String,Observer>();

    public static  List<Host> hostList;//new Hashtable<String,Observer>();

    public static  List<Scheme> schemeList;

    // 通过构造方法给线程名字赋值
    public MonitorThread() {
        super();
        magentMap = new Hashtable<String,Observer>();
        hostService = (HostService) SpringContextUtil.getBean("hostService");
        schemeSvc = (SchemeService) SpringContextUtil.getBean("schemeService");
    }

    @Override
    public void run() {
        while(true){
            try {
                notifyObserver();
                sleep(sleepTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void addObserver(Observer obj) {
        if(MonitorThread.magentMap!=null){
            MonitorThread.magentMap.put(obj.getObserverId(),obj);
        }else{
            MonitorThread.magentMap =  new Hashtable<String,Observer>();
            MonitorThread.magentMap.put(obj.getObserverId(),obj);
        }

    }

    @Override
    public void deleteObserver(Observer obj) {
        if(MonitorThread.magentMap!=null){
            Iterator iter = MonitorThread.magentMap.keySet().iterator();
            while(iter.hasNext()){
                String key = (String) iter.next();
                if(obj.getObserverId().equals(key)){
                    iter.remove();
                    MonitorThread.magentMap.remove(key,obj);
                }
            }
        }
    }

    @Override
    public void notifyObserver() throws Exception{
        //监控线程调度
        notifyMagentThread();
    }

    private void notifyMagentThread(){
        JSONObject result = hostService.getAllHost();
        JSONObject keysTemp = new JSONObject();
        List<MagentThread> delThreadArr = new ArrayList<MagentThread>();
        JSONObject schemes = schemeSvc.getAllScheme();
        if(schemes.getIntValue(Result.CODE)>0 &&  result.getInteger(Result.TOTAL)>0){
            schemeList = (List<Scheme>)schemes.get(Result.ROWS);
        }
        if(result.getInteger(Result.CODE)==1 && result.getInteger(Result.TOTAL)>0){
            //主机有新增和修改逻辑
            hostList = (List<Host>)result.get(Result.ROWS);
            for(Host host :hostList){
                if(host.getHostStatus()==1){
                    keysTemp.put(host.getId()+"",host);
                    MagentThread magentThread = (MagentThread)MonitorThread.magentMap.get(host.getId()+"");
                    if(magentThread!=null){
                        if(magentThread.updateObserver(host)){
                            this.deleteObserver(magentThread);
                            newStartMagentThread(host);
                        }
                    }else{
                        newStartMagentThread(host);
                    }
                }
            }
            //主机有停用或者删除
            Set<String> keys = MonitorThread.magentMap.keySet();
            for(String key:keys){
                if(!keysTemp.containsKey(key)){
                    MagentThread magentThread = (MagentThread)MonitorThread.magentMap.get(key);
                    if(magentThread!=null){
                        //如果主机列表没有该主机，但是线程还是存在，则关闭监控服务，停掉线程，移除map里对应的线程
                        magentThread.shutdownObserver();
                        delThreadArr.add(magentThread);
                    }
                }
            }
        }else{
            //如果没有数据且map的还有线程组，停止map的全部线程
            Set<String> keys = MonitorThread.magentMap.keySet();
            Iterator it = keys.iterator();
            while(it.hasNext()){
                String key = (String)it.next();
                MagentThread magentThread = (MagentThread)MonitorThread.magentMap.get(key);
                if(magentThread!=null){
                    magentThread.shutdownObserver();
                    delThreadArr.add(magentThread);
                }
            }
        }
        //统一删除map无用的线程
        for(MagentThread mt :delThreadArr){
            this.deleteObserver(mt);
        }

    }
    private void newStartMagentThread(Host host) {
        MagentThread magentThread = new MagentThread(host);
        this.addObserver(magentThread);
        magentThread.start();
    }

}
